# -*- coding: utf-8 -*-
"""
    @Author ljy
    @Date 2020/11/5 16:54
    @Describe 
"""
from datetime import datetime
from dbs import Dao

class SecureDao(Dao):
    def __init__(self):
        super(SecureDao,self).__init__()
        self.table = 'tb_user_secure'

    def check_fields(self,*fields,**item):
        fs = set(fields)
        ks = set(item.keys())
        return fs & ks == fs


    def add(self,**item):
        if self.check_fields('title','result','uid',**item):
            item.setdefault('update_date',datetime.now().strftime('%Y-%m-%d'))
            return self.save(self.table,**item)
        raise Exception('数据库的字段不完整')

    def list(self,user_id):
        return self.query(self.table,'title','result','update_date','id',where='uid=%s',args=(user_id,))

    # def update(self, *, user_id,secure_id,title,result) 加*表示后面参数关键字参数传参
    def update(self, **data):
        # data = locals()  # 将局部变量转成字典的key:value结构
        # data.pop('self')
        # data.pop('__class__')

        # data['id'] = data.pop('secure_id')
        # data['uid'] = data.pop('user_id')
        data.setdefault('update_date', datetime.now().strftime('%Y-%m-%d'))
        return super(SecureDao, self).update(self.table,pk='id',extra_where_field='uid',**data)


    def delete(self,**where):
        if not self.check_fields('id','uid',**where):
            raise Exception('条件中必须存在id或uid')
        # where -> id=1,uid=3
        where_sql = ' and '.join([f'{k} =%({k})s' for k in where]) # ' id=%(id)s and uid=%(uid)s'
        return super(SecureDao, self).delete(self.table,where_sql,args=where)

